<template>
  <div class="backend-test">
    <div class="test-container">
      <el-card class="test-card">
        <template #header>
          <div class="card-header">
            <span>后端连接测试</span>
            <el-tag type="info">网络诊断</el-tag>
          </div>
        </template>

        <div class="test-content">
          <!-- 基础连接测试 -->
          <div class="test-section">
            <h3>🔗 基础连接测试</h3>
            <div class="test-grid">
              <div class="test-item">
                <h4>1. 直接访问后端</h4>
                <el-button @click="testDirectBackend" :loading="testing.direct">
                  测试 localhost:8085
                </el-button>
                <div v-if="results.direct" class="result">
                  <el-tag :type="results.direct.success ? 'success' : 'danger'">
                    {{ results.direct.message }}
                  </el-tag>
                </div>
              </div>

              <div class="test-item">
                <h4>2. 通过代理访问</h4>
                <el-button @click="testProxyBackend" :loading="testing.proxy">
                  测试 /housingHub
                </el-button>
                <div v-if="results.proxy" class="result">
                  <el-tag :type="results.proxy.success ? 'success' : 'danger'">
                    {{ results.proxy.message }}
                  </el-tag>
                </div>
              </div>

              <div class="test-item">
                <h4>3. 发送验证码API</h4>
                <el-button @click="testSendCodeApi" :loading="testing.sendCode">
                  测试验证码接口
                </el-button>
                <div v-if="results.sendCode" class="result">
                  <el-tag :type="results.sendCode.success ? 'success' : 'danger'">
                    {{ results.sendCode.message }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>

          <el-divider />

          <!-- 详细信息 -->
          <div class="info-section">
            <h3>📋 连接信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <strong>前端地址:</strong>
                <code>{{ frontendUrl }}</code>
              </div>
              <div class="info-item">
                <strong>后端地址:</strong>
                <code>http://localhost:8085</code>
              </div>
              <div class="info-item">
                <strong>代理路径:</strong>
                <code>/housingHub → http://localhost:8085/housingHub</code>
              </div>
              <div class="info-item">
                <strong>验证码API:</strong>
                <code>POST /housingHub/user/send-code</code>
              </div>
            </div>
          </div>

          <el-divider />

          <!-- 测试日志 -->
          <div class="logs-section">
            <h3>📝 测试日志</h3>
            <div class="logs-container">
              <div v-if="testLogs.length === 0" class="no-logs">
                暂无测试日志
              </div>
              <div v-for="(log, index) in testLogs" :key="index" class="log-item">
                <div class="log-header">
                  <span class="log-time">{{ log.time }}</span>
                  <el-tag :type="log.success ? 'success' : 'danger'" size="small">
                    {{ log.test }}
                  </el-tag>
                </div>
                <div class="log-content">
                  <p><strong>请求:</strong> {{ log.url }}</p>
                  <p><strong>方法:</strong> {{ log.method }}</p>
                  <p><strong>状态:</strong> {{ log.status }}</p>
                  <p><strong>响应:</strong></p>
                  <pre class="log-response">{{ log.response }}</pre>
                </div>
              </div>
            </div>
          </div>

          <!-- 解决方案建议 -->
          <div class="solutions-section">
            <h3>💡 常见问题解决方案</h3>
            <div class="solutions-grid">
              <el-card class="solution-card">
                <h4>🚫 连接被拒绝</h4>
                <ul>
                  <li>检查后端服务是否启动 (localhost:8085)</li>
                  <li>检查防火墙设置</li>
                  <li>确认端口8085未被占用</li>
                </ul>
              </el-card>

              <el-card class="solution-card">
                <h4>❌ 401 未授权</h4>
                <ul>
                  <li>检查API路径是否正确</li>
                  <li>确认后端是否需要特殊请求头</li>
                  <li>检查CORS配置</li>
                </ul>
              </el-card>

              <el-card class="solution-card">
                <h4>🔄 代理问题</h4>
                <ul>
                  <li>重启前端开发服务器</li>
                  <li>检查vite.config.js代理配置</li>
                  <li>清除浏览器缓存</li>
                </ul>
              </el-card>

              <el-card class="solution-card">
                <h4>🌐 CORS错误</h4>
                <ul>
                  <li>检查后端CORS配置</li>
                  <li>确认允许的源地址</li>
                  <li>检查预检请求处理</li>
                </ul>
              </el-card>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'

// 响应式数据
const testing = reactive({
  direct: false,
  proxy: false,
  sendCode: false
})

const results = reactive({
  direct: null,
  proxy: null,
  sendCode: null
})

const testLogs = ref([])

// 计算属性
const frontendUrl = computed(() => window.location.origin)

// 方法
const addLog = (test, method, url, status, response, success) => {
  testLogs.value.unshift({
    time: new Date().toLocaleTimeString(),
    test,
    method,
    url,
    status,
    response: typeof response === 'string' ? response : JSON.stringify(response, null, 2),
    success
  })
  
  // 只保留最近10条日志
  if (testLogs.value.length > 10) {
    testLogs.value = testLogs.value.slice(0, 10)
  }
}

const testDirectBackend = async () => {
  testing.direct = true
  results.direct = null

  try {
    const response = await fetch('http://localhost:8085/housingHub/user/send-code', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ email: 'test@qq.com' }),
      mode: 'cors'
    })

    const responseText = await response.text()
    
    results.direct = {
      success: response.ok,
      message: `状态码: ${response.status} ${response.statusText}`
    }

    addLog('直接连接', 'POST', 'http://localhost:8085/housingHub/user/send-code', 
           response.status, responseText, response.ok)

    if (response.ok) {
      ElMessage.success('直接连接后端成功')
    } else {
      ElMessage.warning(`直接连接返回: ${response.status}`)
    }
  } catch (error) {
    console.error('直接连接失败:', error)
    results.direct = {
      success: false,
      message: `连接失败: ${error.message}`
    }

    addLog('直接连接', 'POST', 'http://localhost:8085/housingHub/user/send-code', 
           'ERROR', error.message, false)

    ElMessage.error('直接连接后端失败')
  } finally {
    testing.direct = false
  }
}

const testProxyBackend = async () => {
  testing.proxy = true
  results.proxy = null

  try {
    const response = await fetch('/housingHub/user/send-code', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ email: 'test@qq.com' })
    })

    const responseText = await response.text()
    
    results.proxy = {
      success: response.ok,
      message: `状态码: ${response.status} ${response.statusText}`
    }

    addLog('代理连接', 'POST', '/housingHub/user/send-code', 
           response.status, responseText, response.ok)

    if (response.ok) {
      ElMessage.success('代理连接后端成功')
    } else {
      ElMessage.warning(`代理连接返回: ${response.status}`)
    }
  } catch (error) {
    console.error('代理连接失败:', error)
    results.proxy = {
      success: false,
      message: `连接失败: ${error.message}`
    }

    addLog('代理连接', 'POST', '/housingHub/user/send-code', 
           'ERROR', error.message, false)

    ElMessage.error('代理连接后端失败')
  } finally {
    testing.proxy = false
  }
}

const testSendCodeApi = async () => {
  testing.sendCode = true
  results.sendCode = null

  try {
    // 使用我们的API服务
    const { sendRegisterCode } = await import('@/utils/apiService')
    const response = await sendRegisterCode('test@qq.com')

    console.log('🔍 验证码发送响应:', response)

    // 响应拦截器返回完整的response对象，实际数据在response.data中
    const responseData = response.data

    results.sendCode = {
      success: responseData.code === 200 || responseData.code === '200',
      message: responseData.message || `业务状态: ${responseData.code}`
    }

    addLog('验证码API', 'POST', '/user/send-code',
           responseData.code, responseData, responseData.code === 200 || responseData.code === '200')

    if (responseData.code === 200 || responseData.code === '200') {
      ElMessage.success('验证码API调用成功')
    } else {
      ElMessage.warning(`验证码API返回: ${responseData.code}`)
    }
  } catch (error) {
    console.error('验证码API失败:', error)
    results.sendCode = {
      success: false,
      message: `API调用失败: ${error.message}`
    }

    addLog('验证码API', 'POST', '/user/send-code', 
           'ERROR', error.message, false)

    ElMessage.error('验证码API调用失败')
  } finally {
    testing.sendCode = false
  }
}
</script>

<style scoped>
.backend-test {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.test-container {
  max-width: 1000px;
  margin: 0 auto;
}

.test-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
  color: #2c3e50;
}

.test-content {
  padding: 20px 0;
}

.test-section h3 {
  color: #409eff;
  margin-bottom: 20px;
}

.test-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.test-item {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}

.test-item h4 {
  color: #2c3e50;
  margin-bottom: 15px;
}

.result {
  margin-top: 10px;
}

.info-section h3 {
  color: #409eff;
  margin-bottom: 15px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.info-item {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.info-item strong {
  color: #2c3e50;
  display: block;
  margin-bottom: 5px;
}

.logs-section h3 {
  color: #409eff;
  margin-bottom: 15px;
}

.logs-container {
  max-height: 400px;
  overflow-y: auto;
}

.no-logs {
  text-align: center;
  color: #909399;
  padding: 40px;
  background: #f8f9fa;
  border-radius: 8px;
}

.log-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.log-time {
  font-size: 12px;
  color: #909399;
}

.log-content p {
  margin: 5px 0;
  color: #2c3e50;
}

.log-response {
  background: #2c3e50;
  color: #fff;
  padding: 10px;
  border-radius: 4px;
  font-size: 11px;
  max-height: 100px;
  overflow-y: auto;
  white-space: pre-wrap;
}

.solutions-section h3 {
  color: #409eff;
  margin-bottom: 20px;
}

.solutions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.solution-card {
  background: #f8f9fa;
}

.solution-card h4 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.solution-card ul {
  margin: 0;
  padding-left: 20px;
}

.solution-card li {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

code {
  background: #f1f2f6;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  color: #e74c3c;
  font-size: 12px;
}
</style>
